package com.benyi.util.scom;

import com.fazecast.jSerialComm.SerialPort;
 
/*8888%*/
public class Client { 
    public static void main(String[] args) {
        SerialPort[] serialPorts = SerialPort.getCommPorts();
 
        if (serialPorts.length == 0) {
            System.out.println("No serial ports found.");
            return;
        }
        
        byte []buffer = new byte[100];
        SerialPort serialPort = serialPorts[1]; // 选择第一个可用的串口
        try {
            serialPort.openPort(); // 打开串口
            serialPort.setComPortParameters(9600, 8, 1, 0); // 设置串口参数（波特率9600, 数据位8, 停止位1, 奇偶校验无）
            serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 10000, 10000); // 设置超时
            String msg="hello!I am M";
            
            int n=0;
            while(true) {
            	msg="Number="+n;
            	byte []b=msg.getBytes();
                int v =serialPort.writeBytes(b, b.length);
                System.out.println("2Send result:"+v);
                int len = serialPort.readBytes(buffer, 100);
                System.out.println("2Read Msg: " + new String(buffer,0,len)); 
                n++;
                Thread.sleep(1024);
            }  
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (serialPort.isOpen()) {
                serialPort.closePort(); // 关闭串口
            }
        }
    }
}
